/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AfMessageService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';

import { CodeGenService } from '../../codegen.service';
import { CgExcelService } from '../cg-excel.service';

@Component({
  selector: 'app-cg-excel-history',
  templateUrl: './cg-excel-history.component.html'
})
export class CgExcelHistoryComponent implements OnInit {
  rows: any[] = [];
  queryParams: any = { fileName: '', fileType: '' };
  isLoading = false;

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'id', sort: true },
    { title: '文件名称', index: 'fileName' },
    { title: '上传标题', index: 'title' },
    { title: '业务类型', index: 'business' },
    // { title: '创建时间', type: 'date', index: 'createdDate' },
    { title: '更新人', index: 'lastModifiedBy' },
    { title: '更新时间', type: 'date', index: 'lastModifiedDate' },
    {
      title: '状态',
      type: 'badge',
      index: 'syncCode',
      badge: {
        9: { text: '待处理', color: 'processing' },
        0: { text: '成功', color: 'success' },
        1: { text: '失败', color: 'error' }
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '下载文件',
          icon: 'download',
          tooltip: `下载原始文件`,
          click: (record, _modal) => {
            this.downloadFile(record);
          }
        },
        {
          text: '更多',
          children: [
            { text: '脚本日志', icon: 'eye', click: (item: any) => this.viewLog(item) },
            {
              text: '删除',
              icon: 'delete',
              type: 'del',
              tooltip: `删除此记录`,
              pop: {
                title: '您确定要删除此记录吗？',
                okType: 'danger',
                icon: 'star'
              },
              click: (record, _modal) => {
                this.delete(record);
              }
            },
            {
              text: '查看JSON',
              icon: 'bug',
              click: (record, _modal) => {
                this.viewJson(record);
              }
            }
          ]
        }
      ]
    }
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    private msg: AfMessageService,
    private cgExcelService: CgExcelService,
    private codegen: CodeGenService,
    private modal: ModalHelper,
    private router: Router,
    private modalForm: NzModalService,
    private xlsxService: XlsxService
  ) {}
  ngOnInit() {
    console.log('dd');
  }

  public query() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.cgExcelService.queryHistory(this.queryParams.fileName, this.queryParams.fileType).subscribe(body => {
        if (body.total >= 1) {
          this.rows = [];
          this.rows = body.list;
        } else {
          this.msg.notice_warning('查询文件', `无数据`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  downloadJpaZip(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.cgExcelService.downloadJpaZip(record.id, true);
      window.open(url);
    } finally {
      this.cdr.detectChanges();
    }
  }

  executeScript(record: any = {}) {
    try {
      this.cgExcelService.executeScript(record.id, '', '', true).subscribe(body => {
        if (body.status) {
          this.msg.notice_success('表结构创建成功', ``);
          // this.query();
          record.sysStatus = body.status;
          record.syncCode = body.code;
          record.syncMsg = body.msg;
        } else {
          this.msg.notice_warning('表结构创建失败', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  delete(item: any) {
    try {
      this.cgExcelService.delete(item.id).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('历史记录', `${item.fileName} 记录删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('历史记录', `${item.fileName} 删除失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  viewLog(record: any = {}) {
    this.router.navigateByUrl(`/codegen/database/script/log?sourceId=${record.id}`);
  }

  downloadFile(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.cgExcelService.getDownloadFileUrl(record.id, true);
      window.open(url);
    } finally {
      this.cdr.detectChanges();
    }
  }

  // 查看当然记录 -- 用于开发测试
  viewJson(record: any = {}) {
    this.codegen.viewJson(record);
  }
}
